<?php

namespace App\HttpController\Api;

use App\Model\Video as VideoModel;
use EasySwoole\Validate\Validate;
use EasySwoole\Http\Message\Status;
use App\Lib\AliyunSdk\AliVod;
use EasySwoole\EasySwoole\Task\TaskManager;
use \EasySwoole\Component\Di;

class Video extends Base
{

    public function index()
    {
        $params = $this->request()->getRequestParam();
        $id = $params['id'];
        $modelObj = new VideoModel();
        $data = $modelObj->getById($id);
        $task = TaskManager::getInstance();
        $task->async(function () use($id){
            Di::getInstance()->get('REDIS')->zincrby(\Yaconf::get('redis.video_play_key'),1,$id);
        });
        return $this->writeJson(200,'OK',$data);
    }

    public function rank()
    {
        $result = Di::getInstance()->get('REDIS')->zrevrange(\Yaconf::get('redis.video_play_key'), 0, -1, true);
        return $this->writeJson(200,'OK',$result);
    }

    public function love()
    {
        $params = $this->request()->getRequestParam();
        $id = $params['id'];
        $result = Di::getInstance()->get('REDIS')->zrevrange(\Yaconf::get('redis.video_love'), 0, -1, true);
        return $this->writeJson(200,'OK',$result);
    }

    public function add()
    {
        $params = $this->request()->getRequestParam();
        $valitor = new Validate();
        $valitor->addColumn('name', '名字不为空')->required('名字不为空');
        $valitor->addColumn('url', 'url不为空')->required('url不为空');
        $valitor->addColumn('image', '图片不为空')->required('图片不为空');
        $valitor->addColumn('content', '内容不为空')->required('内容不为空');
        $valitor->addColumn('cat_id', 'cat_id格式错误')->integer('cat_id格式错误');
        $valitor->addColumn('status', '状态格式错误')->integer('状态格式错误');
        $data = [
            'name' => $params['name'],
            'url' => $params['url'],
            'image' => $params['image'],
            'content' => $params['content'],
            'cat_id' => $params['cat_id'],
            'create_time' => time(),
            'status' => 1,
        ];
        if(!$valitor->validate($data)){
            return $this->writeJson(Status::CODE_BAD_REQUEST,$valitor->getError()->__toString());
        }
        try{
            $modelObj = new VideoModel();
            $videoId = $modelObj->add($data);
        }catch(\Exception $e){
            return $this->writeJson(Status::CODE_BAD_REQUEST,$e->getMessage(),[]);
        }
        if(!empty($videoId)){
            return $this->writeJson(Status::CODE_OK,'ok',['id' => $videoId]);
        }else{
            return $this->writeJson(Status::CODE_BAD_REQUEST,'',['id' => $videoId]);
        }
    }

}